package com.xcw.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import com.xcw.base.dto.UserDto;
import com.xcw.entity.User;
import com.xcw.mapstruct.UserMapper;
import com.xcw.repository.UserRepository;
import com.xcw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @Author bhx
 * @Date 2022/8/28 23:09
 * @Description TODO
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    UserRepository userRepository;

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDto register(String openid) {
        Assert.isTrue(openid != null,"不合法注册条件");
        User user = userRepository.findByOpenId(openid);
        if (user == null){
            user = new User();
            user.setUsername("Hub-"  + RandomUtil.randomString(5));
            user.setAvatar("https://img1.baidu.com/it/u=873106765,2587410047&fm=253&fmt=auto&app=138&f=JPEG?w=530&h=500 ");
            user.setLasted(LocalDateTime.now());
            user.setOpenId(openid);
        }else {
            user.setLasted(LocalDateTime.now());
        }
        userRepository.save(user);
        return  userMapper.toDto(user);
    }
}
